import { Button, FormInstance, Layout, message } from 'antd';
import React from 'react';

import { IsDraft } from '../../constant';
import { Info, TemplateDetailInfoBE } from '../../interface';
import { hasEmptyOrAllHiddenProductImageLayer } from '../../utils';

const { Footer } = Layout;

interface TemplateFooterProps {
  canSave: boolean;
  infoForm: FormInstance<Info>;
  templateDetail: Partial<TemplateDetailInfoBE>;
  onLeave: () => boolean;
  saveTemplateInfo: (isDraft: IsDraft) => Promise<void>;
}

const TemplateFooter = (props: TemplateFooterProps): JSX.Element => {
  const { canSave, infoForm, templateDetail, onLeave, saveTemplateInfo } =
    props;

  const handleTemplateSave = async (): Promise<void> => {
    try {
      await infoForm.validateFields();
    } catch (error) {
      message.error('Template name error, please check again.');
      return;
    }

    if (hasEmptyOrAllHiddenProductImageLayer(templateDetail.feLayers || [])) {
      message.error(
        'A minimum of 1 visible product image placement is required to proceed.'
      );
      return;
    }

    saveTemplateInfo(IsDraft.NotDraft);
  };

  return (
    <Footer className="bg-white flex justify-end gap-x-4 py-3 px-4">
      <Button onClick={onLeave}>Cancel</Button>
      <Button type="primary" disabled={!canSave} onClick={handleTemplateSave}>
        Save
      </Button>
    </Footer>
  );
};

export default TemplateFooter;
